<template>
  <div class="category-index">
    <div class="head">
        <div class="search">
            <div class="name">
                <label class="label">分类名称：</label>
                <el-input :clearable="true" @clear="getCategory" v-model="categoryName" placeholder="请填写分类名称"></el-input>
            </div>
            <div class="type">
                <label class="label">分类类型：</label>
                <el-select :clearable="true" @clear="getCategory" v-model="categoryType" placeholder="请选择分类类型">
                    <el-option
                    v-for="item in categoryOptions" :key="item.value"
                    :value="item.value"
                    :label="item.label"></el-option>
                </el-select>
            </div>
            <el-button @click="getCategory" class="black">查询</el-button>
        </div>
        <div class="add">
            <el-button @click="openAddDishDialog = true" class="black">+ 新增菜品分类</el-button>
            <el-button @click="openAddSetmealDialog = true" type="primary">+ 新增套餐分类</el-button>
        </div>
    </div>
    <div v-if="categoryList.length !== 0" class="main">
        <el-table :data="categoryList">
            <el-table-column prop="name" align="center" label="分类名称"></el-table-column>
            <el-table-column prop="type" align="center" label="分类类型">
                <template slot-scope="scope">{{ scope.row.type === 1 ? '菜品分类' : '套餐分类' }}</template>
            </el-table-column>
            <el-table-column prop="sort" align="center" label="排序"></el-table-column>
            <el-table-column prop="status" align="center" label="状态">
                <template slot-scope="scope">
                    <div class="tableColumn-status" :class="{ active: scope.row.status === 1 }">
                        <span>{{ scope.row.status === 1 ? '启售' : '停售' }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" align="center" label="操作时间"></el-table-column>
            <el-table-column class-name="operate" align="center" label="操作时间">
                <template slot-scope="scope">
                    <button class="btn" @click="handleEditCategory(scope.row.type, scope.row.name, scope.row.sort, scope.row.id)">修改</button>
                    <button class="btn red" @click="deleteCategory(scope.row.id)">删除</button>
                    <button @click="changeStatus(scope.row.status, scope.row.id)" v-if="scope.row.status === 0" class="btn">启用</button>
                    <button @click="changeStatus(scope.row.status, scope.row.id)" v-else class="btn red">禁用</button>
                </template>
            </el-table-column>
        </el-table>
        <div class="paginate">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :total="pageTotal"
            :page-size.sync="pageSize"
            :current-page.sync="page"
            @size-change="getCategory()"
            @current-change="getCategory()"
            ></el-pagination>
        </div>
    </div>
    <div v-else class="main">
        <div class="empty">
            <img class="empty-pic" src="@/assets/search_table_empty.png" alt="">
            <span class="hint">这里空空如也~</span>
        </div>
    </div>
    <!-- 新增菜品弹窗 -->
    <el-dialog
     title="新增菜品分类"
     :visible.sync="openAddDishDialog"
     width="30%"
     @close="handleDialogClose">
        <template>
            <el-form ref="addCategoryForm" :model="rulesData" :rules="rules">
                <el-form-item prop="addCategoryName" label="分类名称：">
                    <el-input v-model="rulesData.addCategoryName" placeholder="请输入分类名称"></el-input>
                </el-form-item>
                <el-form-item prop="sort" label="排序：">
                    <el-input v-model="rulesData.sort" placeholder="请输入排序"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <div slot="footer" class="dialog-footer">
            <el-button @click="openAddDishDialog = false">取消</el-button>
            <el-button @click="handleAddCategory(1, false)" class="black">确定</el-button>
            <el-button v-show="isEditStatus === false" @click="handleAddCategory(1, true)" type="primary">保存并进行添加</el-button>
        </div>
    </el-dialog>
    <!-- 新增套餐弹窗 -->
    <el-dialog
     title="新增套餐分类"
     :visible.sync="openAddSetmealDialog"
     width="30%"
     custom-class="setmealDialog">
          <template>
            <el-form ref="addCategoryForm" :model="rulesData" :rules="rules">
                <el-form-item prop="addCategoryName" label="分类名称：">
                    <el-input v-model="rulesData.addCategoryName" placeholder="请输入分类名称"></el-input>
                </el-form-item>
                <el-form-item prop="sort" label="排序：">
                    <el-input v-model="rulesData.sort" placeholder="请输入排序"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <div slot="footer" class="dialog-footer">
            <el-button @click="openAddDishDialog = false">取消</el-button>
            <el-button @click="handleAddCategory(2, false)" class="black">确定</el-button>
            <el-button v-show="isEditStatus === false" @click="handleAddCategory(2, true)" type="primary">保存并进行添加</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategory, changeStatus, deleteCategory, addCategory, editCategory } from '@/api/category'
export default {
  name: 'CategoryIndex',
  data () {
    const validateCategoryName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('新增菜品分类不能为空'))
      }

      const reg = /^[\u4e00-\u9fa5A-Za-z0-9]{2,20}$/
      if (!reg.test(value)) {
        callback(new Error('分类名称输入不符，请输入2-20个字符'))
      }
      callback()
    }
    const validateSort = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('排序不能为空'))
      }

      const reg = /^\d+$/
      if (!reg.test(value)) {
        callback(new Error('排序只能输入数字类型'))
      }
      callback()
    }
    return {
      categoryOptions: [
        { value: 1, label: '菜品分类' },
        { value: 2, label: '套餐分类' }
      ],
      categoryName: '',
      categoryType: '',
      pageTotal: 0,
      pageSize: 10,
      page: 1,
      categoryList: [],
      openAddDishDialog: false,
      rulesData: {
        addCategoryName: '',
        sort: ''
      },
      rules: {
        addCategoryName: [
          { validator: validateCategoryName, required: true, trigger: 'blur' }
        ],
        sort: [
          { validator: validateSort, required: true, trigger: 'blur' }
        ]
      },
      openAddSetmealDialog: false,
      isEditStatus: false,
      editCategoryInfo: {
        type: '',
        id: ''
      }
    }
  },
  created () {
    this.getCategory()
  },
  methods: {
    async getCategory () {
      const res = await getCategory({
        name: this.categoryName,
        type: this.categoryType,
        page: this.page,
        pageSize: this.pageSize
      })
      console.log(res)

      if (res.code === 1) {
        this.categoryList = res.data.records
        this.pageTotal = res.data.total
      }
    },
    changeStatus (status, id) {
      this.$confirm('确认调整该分类的状态？', '提示', {}).then(async () => {
        const res = await changeStatus(status ? 0 : 1, id)
        if (res.code === 1) {
          this.getCategory()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {})
    },
    deleteCategory (id) {
      this.$confirm('此操作将永久删除该分类，是否继续？', '确定删除', {}).then(async () => {
        const res = await deleteCategory(id)
        if (res.code === 1) {
          this.getCategory()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {})
    },
    async handleAddCategory (type, isContinueAdd) {
      if (!this.isEditStatus) {
        const res = await addCategory({
          name: this.rulesData.addCategoryName,
          sort: this.rulesData.sort,
          type
        })
        if (res.code === 1) {
          this.getCategory()
          this.$message.success('操作成功')
          type === 1 ? isContinueAdd || (this.openAddDishDialog = false) : isContinueAdd || (this.openAddSetmealDialog = false)
        } else {
          this.$message.error(res.msg)
        }
      } else {
        const res = await editCategory({
          id: this.editCategoryInfo.id,
          type: this.editCategoryInfo.type,
          name: this.rulesData.addCategoryName,
          sort: this.rulesData.sort
        })
        if (res.code === 1) {
          this.getCategory()
          this.$message.success('操作成功')
          this.openAddSetmealDialog = false
          this.openAddDishDialog = false
          this.isEditStatus = false
        } else {
          this.$message.error(res.msg)
        }
      }
      this.rulesData.addCategoryName = ''
      this.rulesData.sort = ''
    },
    handleEditCategory (type, name, sort, id) {
      if (type === 1) {
        this.openAddDishDialog = true
      } else if (type === 2) {
        this.openAddSetmealDialog = true
      }
      this.isEditStatus = true
      this.rulesData.addCategoryName = name
      this.rulesData.sort = sort
      this.editCategoryInfo.type = type
      this.editCategoryInfo.id = id
    },
    handleDialogClose () {
      this.rulesData.addCategoryName = ''
      this.rulesData.sort = ''
    }
  }
}
</script>

<style lang="less" scoped>
.category-index {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;

    .head {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        font-size: 14px;

        // 黑色按钮
        .el-button.black {
            color: #fff;
            background-color: #333;
            border-color: #333;

            &:hover {
                background-color: #666;
            }

            &:active {
                background-color: #333;
            }
        }

        .search {
            display: flex;
            align-items: center;
            gap: 15px;

            > div {
                display: flex;
                align-items: center;

                .label {
                    flex-shrink: 0;
                    margin-right: 5px;
                }
            }

            .el-input {
                width: 240px;
            }
        }
    }

    .main {
        margin-top: 20px;

        ::v-deep .el-table {
            thead th:nth-of-type(6) {
                border-right: 1px solid #ebeef5;
            }
        }

        .empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            margin-top: 200px;
            padding-bottom: 100px;

            .empty-pic {
                width: 250px;
                height: auto;
            }

            .hint {
                font-size: 14px;
                color: #666;
            }
        }
    }

    ::v-deep .el-dialog {
        .el-dialog__body {
            padding: 30px 20px 10px 20px;

            .el-form .el-form-item {
                display: flex;

                .el-form-item__label {
                    min-width: 100px;
                }

                .el-form-item__content {
                    flex: 1;
                }
            }
        }

        .el-dialog__footer {
            .dialog-footer {
                .el-button.black {
                    background-color: #333;
                    color: #fff;
                    border-color: transparent;
                }

                .el-button.black:hover {
                    background-color: #666;
                }

                .el-button.black:active {
                    background-color: #333;
                }
            }
        }
    }
}
</style>
